﻿///////////////////////////////////////////////////////////////////////////////
// File:        Thread.hpp
// Author:      671643387@qq.com
// Description:
///////////////////////////////////////////////////////////////////////////////

#ifndef NIO_BASE_THREAD_HPP_
#define NIO_BASE_THREAD_HPP_

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif

#include <boost/noncopyable.hpp>

#if defined(__WINDOWS__)
#include <process.h>
#elif defined(__LINUX__)
#include <pthread.h>
#endif

namespace nio
{
    namespace base
    {
        class Thread : public boost::noncopyable
        {
        public:
#if defined(__WINDOWS__)
            typedef unsigned int    id;
#elif defined(__LINUX__)
            typedef pthread_t       id;
#endif
            enum State
            {
                READY,
                RUNNING,
                EXIT
            };

        public:
            Thread(void);
            virtual ~Thread(void);

            bool start(void);
            virtual void run(void) = 0;
            virtual void stop(void){}

            void join(void);
            bool joinable(void);
            void detach(void);

            State getState(void) const { return state_; }
            id getId(void) const { return id_; }

            static void sleep(unsigned int ms);
            static id currentTid(void);
        private:
            void setState(State state) { state_ = state; }

#if defined(__WINDOWS__)
            static unsigned int __stdcall thread_proc(void* arg);
#elif defined(__LINUX__)
            static void* thread_proc(void* arg);
#endif

        private:
            id          id_;
            State       state_;
#if defined(__WINDOWS__)
            ::uintptr_t handle_;
#endif
        };
    }
}

#endif //NIO_BASE_THREAD_HPP_
